import { ref, onMounted, onBeforeUnmount, Ref } from 'vue'
import { debounce } from './common'

interface ResizeOptions {
  chart?: Ref<any>
  debounceTime?: number
}

export function useResize(options: ResizeOptions = {}) {
  const { chart, debounceTime = 100 } = options
  const sidebarElm = ref<HTMLElement | null>(null)
  const resizeHandler = ref<(() => void) | null>(null)

  const resize = () => {
    if (chart?.value) {
      chart.value.resize()
    }
  }

  const sidebarResizeHandler = (e: TransitionEvent) => {
    if (e.propertyName === 'width') {
      resizeHandler.value?.()
    }
  }

  const initListener = () => {
    resizeHandler.value = debounce(() => {
      resize()
    }, debounceTime)
    
    window.addEventListener('resize', resizeHandler.value)

    sidebarElm.value = document.getElementsByClassName('sidebar-container')[0] as HTMLElement
    if (sidebarElm.value) {
      sidebarElm.value.addEventListener('transitionend', sidebarResizeHandler)
    }
  }

  const destroyListener = () => {
    if (resizeHandler.value) {
      window.removeEventListener('resize', resizeHandler.value)
      resizeHandler.value = null
    }

    if (sidebarElm.value) {
      sidebarElm.value.removeEventListener('transitionend', sidebarResizeHandler)
    }
  }

  onMounted(() => {
    initListener()
  })

  onBeforeUnmount(() => {
    destroyListener()
  })

  return {
    resize,
    initListener,
    destroyListener
  }
}